﻿using NDK.Communacation;
using NDK.Laser;
using NDK.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace NDK.AcqDevice.Keyence
{
    public class PointLaser : IDevice, IPointLaser
    {
        #region 变量
        AutoResetEvent recieveEvent = new AutoResetEvent(false);
        SerialPort _port = new SerialPort();
        ECommunacation communication = null;
        string COM = string.Empty;
        private string _vaule = string.Empty;

        public event PropertyChangedEventHandler PropertyChanged;
        private string _status = string.Empty;
        public string Status
        {
            get
            {
                return _status;
            }
            private set
            {
                _status = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(value.ToString()));
            }
        }
        #endregion
        #region 方法
        private string GetVaule(int timeout = 3000)
        {
            if (recieveEvent.WaitOne(timeout) == true)
            {
                return _vaule;

            }
            return "Timeout";
        }
        public bool IsConnected
        {
            get
            {
                return communication.IsConnected;
            }
        }
        public PointLaser(string com)
        {
            COM = com;
            recieveEvent.Reset();
        }
        /// <summary>
        /// 打开
        /// </summary>
        public bool Open()
        {
            try
            {
                recieveEvent.Reset();
                Status = $"PointLaser （通讯口{COM}) Connecting...";

                if (COM.Contains("."))
                {
                    try
                    {
                        communication?.DisConnect();
                        string laserCom = EComManageer.CreateECom(CommunicationModel.TcpClient);
                        communication = EComManageer.GetECommunacation(laserCom);
                        communication.RemoteIP = COM;
                        communication.RemotePort = 24687;
                        communication.ReceiveString += ReceiveString;
                        EComManageer.Connect(laserCom);
                        return true;
                    }
                    catch (Exception ex)
                    {
                        Status = $"PointLaser （通讯口{COM}) Connect Exception Message:{ex.Message} Exception StackTrace {ex.StackTrace}";
                        return false;
                    }
                }
                try
                {
                    communication?.DisConnect();
                    string laserCom = EComManageer.CreateECom(CommunicationModel.COM);
                    communication = EComManageer.GetECommunacation(laserCom);
                    communication.SerialNo = COM;

                    string comParam = "57600,0,8,1,\r";
                    string[] arg = comParam.Trim().Split(',');

                    _port.BaudRate = int.Parse(arg[0].Trim());
                    _port.Parity = Parity.Even;
                    _port.DataBits = int.Parse(arg[2].Trim());
                    _port.StopBits = (StopBits)int.Parse(arg[3].Trim());
                    _port.Handshake = Handshake.None;


                    communication.ReceiveString += ReceiveString;
                    EComManageer.Connect(laserCom);
                    return true;
                }
                catch (Exception ex)
                {
                        Status = $"PointLaser （通讯口{COM}) Connect Exception Message:{ex.Message} Exception StackTrace {ex.StackTrace}";
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        private void ReceiveString(string str)
        {
            Status = $"PointLaser （通讯口{COM}) ReceiveString：{str}";
            StringProcess(str);
        }

        private void StringProcess(string str)
        {
            string[] data = str.Split('\r')[0].Split(',');
            string laserData = null;
            if (data != null && data.Length != 0)
            {
                laserData = data[1];
                this._vaule = laserData;
                recieveEvent.Set();
            }
        }


        /// <summary>
        /// 读取指定通道的值
        /// </summary>
        /// <param name="index">通道：0,1,2,3</param>
        /// <param name="timeout">读取超时的时间</param>
        /// <returns>返回读取到的值</returns>
        public string Read(int index, int timeout = 3000)
        {
            communication.SendStr($"M{index}" + Environment.NewLine);
            Status = "SendStr: " + $"M{index}";
            string val = GetVaule(timeout);
            Status = val;
            return val;
        }

      
        #endregion 方法


    }

}
